<template>
  <div class="system-edit-location-container">
    <el-dialog :title="(ruleForm.id!==0?'修改':'添加')+'地址'" v-model="isShowDialog" width="600">
      <el-row>
        <div id="amap-container" class="amap-container"></div>
      </el-row>
      <div class="detail-wrap">
        <p>地址：{{ruleForm.location}}</p>
        <p>国家：{{ruleForm.country}}</p>
        <p>省市区：{{ruleForm.province}}.{{ruleForm.city}}.{{ruleForm.district}}</p>
        <p>市级编码：{{ruleForm.adcode}}</p>
        <p>区县编码：{{ruleForm.citycode}}</p>
        <p>经纬度：{{ruleForm.longitude}},{{ruleForm.latitude}}</p>
      </div>
      <template #footer>
				<span class="dialog-footer">
					<el-button @click="onCancel" size="default">取 消</el-button>
					<el-button type="primary" @click="onSubmit"
                     size="default">{{ ruleForm.id !== 0 ? '修 改' : '添 加' }}</el-button>
				</span>
      </template>
    </el-dialog>
  </div>
</template>

<script lang="ts">
import {reactive, toRefs, onMounted, defineComponent, ref, unref, onBeforeMount, nextTick} from 'vue';
import {ElMessage} from "element-plus";
import {addLocation, getLocation, updateLocation} from "/@/api/system/location";

export default defineComponent({
  name: 'systemEditLocation',
  props: {
    actType: {
      type: String,
      default: () => 'add'
    }
  },
  setup(prop, {emit}) {
    const formRef = ref<HTMLElement | null>(null);
    const state = reactive({
      isShowDialog: false,
      groups: [],
      ruleForm: {
        id: 0,
        location: '成都市双流区黄金时代',
        citycode: null,
        adcode: null,
        longitude: null,
        latitude: null,
        country: null,
        province: null,
        city: null,
        district: null,
        street: null,
      },
      //表单校验
      rules: {
        location: [
          {required: true, message: "地址信息不能为空", trigger: "blur"}
        ],
      },
      amapInstance: null,
      amapMarker: null,
      geoCoder: null
    });
    onBeforeMount(() => {
      // setTimeout(() => {
      //   initMap()
      // }, 300)
    });
    const initMap = async () => {
      let _lngLat = [state.ruleForm.longitude, state.ruleForm.latitude]
      let _cityCode = state.ruleForm.citycode
      state.amapInstance = new AMap.Map('amap-container', {
        features: ['bg', 'road', 'building', 'point'],
        center: _lngLat,
        zoom: 13,
        viewMode: '2D'
      })
      state.amapInstance.on('click', function (e) {
        state.ruleForm.longitude = e.lnglat.lng
        state.ruleForm.latitude = e.lnglat.lat
        getCoder(_cityCode, [e.lnglat.lng, e.lnglat.lat])
      })
      getCoder(_cityCode, _lngLat)
    };
    const getCoder = (_cityCode, _lngLat) => {
      if (state.amapMarker !== null) {
        state.amapInstance.remove(state.amapMarker)
      }
      // 创建一个 Marker 实例：
      // eslint-disable-next-line
      state.amapMarker = new AMap.Marker({
        icon: '//a.amap.com/jsapi_demos/static/demo-center/icons/poi-marker-red.png',
        position: _lngLat
      })
      // 将创建的点标记添加到已有的地图实例：
      state.amapInstance.add(state.amapMarker)
      if (state.geoCoder === null) {
        // eslint-disable-next-line
        state.geoCoder = new AMap.Geocoder({
          city: _cityCode, // 城市设为北京，默认：“全国”
          radius: 1000 // 范围，默认：500
        })
      }
      state.geoCoder.getAddress(_lngLat, function (status, result) {
        if (status === 'complete' && result.regeocode) {
          // console.log(result.regeocode)
          let _response = result.regeocode
          state.ruleForm.location = _response.formattedAddress
          state.ruleForm.country = _response.addressComponent.country
          state.ruleForm.province = _response.addressComponent.province
          state.ruleForm.city = _response.addressComponent.city
          state.ruleForm.citycode = _response.addressComponent.citycode
          state.ruleForm.adcode = _response.addressComponent.adcode
          state.ruleForm.district = _response.addressComponent.district
          state.ruleForm.street = _response.addressComponent.township + _response.addressComponent.street + _response.addressComponent.streetNumber
        } else {
          state.ruleForm.location = '加载地址失败'
          state.ruleForm.country = ''
          state.ruleForm.province = ''
          state.ruleForm.city = ''
          state.ruleForm.citycode = ''
          state.ruleForm.adcode = ''
          state.ruleForm.district = ''
          state.ruleForm.street = ''
        }
      })
    };
    // 打开弹窗
    const openDialog = (row?: any) => {
      resetForm();
      if (row?.id) {
        getLocation({id: row.id}).then((res: any) => {
          const _data = res.data
          state.ruleForm = {
            id: _data.id,
            location:  _data.location,
            citycode:  _data.citycode,
            adcode:  _data.adcode,
            longitude:  _data.longitude,
            latitude:  _data.latitude,
            country: _data.country,
            province: _data.province,
            city: _data.city,
            district: _data.district,
            street: _data.street,
          };
          initMap()
        })
      } else {
        state.ruleForm.latitude =  30.537115;
        state.ruleForm.longitude = 104.09028;
        nextTick(() => {
          initMap();
        });
      }
      state.isShowDialog = true;
    };
    // 关闭弹窗
    const closeDialog = () => {
      state.isShowDialog = false;
    };
    // 取消
    const onCancel = () => {
      closeDialog();
    };
    // 新增
    const onSubmit = () => {
      const formWrap = unref(formRef) as any;
      if (!formWrap) return;
      formWrap.validate((valid: boolean) => {
        if (valid) {
          if (state.ruleForm.id === 0) {
            //添加
            addLocation(state.ruleForm).then(() => {
              ElMessage.success('添加地址成功');
              closeDialog(); // 关闭弹窗
              emit('callback')
            });
          } else {
            //修改
            updateLocation(state.ruleForm).then(() => {
              ElMessage.success('修改地址成功');
              closeDialog(); // 关闭弹窗
              emit('callback')
            });
          }
        }
      });
    };
    // 页面加载时
    onMounted(() => {
      // initTableData();
    });
    const resetForm = () => {
      state.amapInstance = null;
      state.amapMarker = null;
      state.geoCoder = null;
      state.ruleForm = {
        id: 0,
        location: null,
        citycode: null,
        adcode: null,
        longitude: null,
        latitude: null,
        country: null,
        province: null,
        city: null,
        district: null,
        street: null,
      }
    };
    return {
      openDialog,
      closeDialog,
      onCancel,
      onSubmit,
      formRef,
      ...toRefs(state),
    };
  },
});
</script>
<style scoped lang="scss">
.system-edit-location-container{
  .amap-container{
    width: 100%;
    height: 400px;
  }
  .detail-wrap{
    margin-top: 20px;
  }
}
</style>
